package com.fanketly.module_safe_photo.domain

import com.blankj.utilcode.util.LogUtils
import com.fanketly.module_safe_photo.data.model.SafePhotoModel
import com.fanketly.module_safe_photo.data.model.SafePhotoSortModel
import com.fanketly.module_safe_photo.data.repo.SafePhotoRepo
import fanketly.core.lib.base.domain.MviDispatcherKTX

/**
 *Create by Fanketly on 2022/9/13
 *Gitee:https://gitee.com/fanketly
 *desc:
 */
class SafePhotoRequester : MviDispatcherKTX<SafePhotoEvent>() {
    private val safeRepo by lazy { SafePhotoRepo() }

    override suspend fun onHandle(event: SafePhotoEvent) {
        when (event) {
            is SafePhotoEvent.AddPhotoSort -> {
                event.any?.let {
                    safeRepo.addPhotoSort(it)
                    LogUtils.d(it.position)
                }
                sendResult(event)
            }
            is SafePhotoEvent.DeletePhotoSort -> TODO()
            is SafePhotoEvent.EditPhotoSort -> {
                event.model?.let {
                    if (safeRepo.updatePhotoSort(it) >= 0) sendResult(event.copy())
                    else sendResult(event.copy(isSuccess = false))
                }
            }
            is SafePhotoEvent.GetPhotoSortList -> sendResult(event.copy(safeRepo.getAllPhotoSort()))
            /**/
            is SafePhotoEvent.GetPhotoList -> sendResult(
                event.copy(
                    list = safeRepo.getPhotoBySortPosition(
                        event.sortPosition
                    )
                )
            )
            is SafePhotoEvent.SwitchPhoto -> {
                event.sourceModel?.let {
                    if ((if (it is SafePhotoModel) safeRepo.updatePhoto(it)
                        else safeRepo.updatePhotoSort(it as SafePhotoSortModel)) >= 0
                    ) {
                        sendResult(event.copy())
                    } else {
                        sendResult(event.copy(isSuccess = false))
                    }
                }
            }

            is SafePhotoEvent.DeletePhoto -> {
                event.basePhotoModel?.let {
                    if ((if (it is SafePhotoModel) safeRepo.deletePhoto(it)
                        else safeRepo.deletePhotoSort(it as SafePhotoSortModel)) >= 0
                    ) {
                        sendResult(event.copy())
                    } else {
                        sendResult(event.copy(isSuccess = false))
                    }
                }
//                if (safeRepo.deletePhoto(event.safePhotoModel!!) >= 0) {
//                    sendResult(event)
//                } else {
//                    sendResult(event.copy(isSuccess = false))
//                }
            }
            is SafePhotoEvent.AddPhoto -> {
                event.any?.let {
                    safeRepo.addPhoto(it)
                    LogUtils.d(it.position)
                }
                sendResult(event)
            }
        }
    }
}